package com.future.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.future.domain.DTO.PermissionDTO;
import com.future.domain.Permission;
import com.future.domain.Result;
import com.future.mapper.PermissionMapper;
import com.future.service.IPermissionService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Override
    public Result listPermissions() {
        List<Permission> permissionList = this.list();
        List<PermissionDTO> permissionDTOList = permissionList.stream()
                .map(permission -> {
                    PermissionDTO permissionDTO =new PermissionDTO();
                    BeanUtil.copyProperties(permission,permissionDTO);
                    return permissionDTO;
                })
                .collect(Collectors.toList());
        return Result.ok(permissionDTOList);
    }

    @Override
    public Result getPermissionById(Long id) {
        Permission permission = this.getById(id);
        if(permission!=null){
            PermissionDTO permissionDTO =new PermissionDTO();
            BeanUtil.copyProperties(permission,permissionDTO);
            return Result.ok(permissionDTO);
        }
        return Result.fail("未找到该权限");
    }

    @Override
    public Result savePermission(PermissionDTO permissionDTO) {
        // 1. 校验DTO必填字段（前端必须传入的参数）
        if (permissionDTO.getPermissionName() == null || permissionDTO.getPermissionCode() == null) {
            return Result.fail("权限名称和权限编码为必填项");
        }

        try {
            // 2. DTO转实体，自动填充后端维护字段
            Permission permission = new Permission();
            BeanUtil.copyProperties(permissionDTO, permission); // 仅复制DTO中存在的字段（如permissionName、permissionCode）
            permission.setCreatedAt(LocalDateTime.now()); // 后端自动生成创建时间

            // 3. 保存实体
            boolean success = this.save(permission);
            return success ? Result.ok("新增权限成功") : Result.fail("新增权限失败");
        } catch (Exception e) {
            return Result.fail("新增权限异常：" + e.getMessage());
        }
    }

    @Override
    public Result updatePermission(PermissionDTO permissionDTO) {
        // 1. 校验DTO：更新必须传入id，且必填字段不为空
        if (permissionDTO.getId() == null || permissionDTO.getPermissionName() == null || permissionDTO.getPermissionCode() == null) {
            return Result.fail("更新权限失败：ID、权限名称和权限编码为必填项");
        }

        try {
            // 2. DTO转实体，自动更新后端维护字段
            Permission permission = new Permission();
            BeanUtil.copyProperties(permissionDTO, permission); // 仅复制DTO中允许更新的字段
            permission.setCreatedAt(LocalDateTime.now());// 后端自动更新时间

            // 3. 更新实体
            boolean success = this.updateById(permission);
            return success ? Result.ok("更新权限成功") : Result.fail("更新权限失败");
        } catch (Exception e) {
            return Result.fail("更新权限异常：" + e.getMessage());
        }
    }


    @Override
    public Result deletePermission(Long id) {
        // 1. 校验ID是否为空
        if (id == null) {
            return Result.fail("删除失败：权限ID不能为空");
        }

        try {
            // 2. 校验权限是否存在
            Permission existingPermission = this.getById(id);
            if (existingPermission == null) {
                return Result.fail("删除失败：未找到ID为" + id + "的权限");
            }

            // 3. 执行删除操作
            boolean success = this.removeById(id);
            return success ? Result.ok("删除权限成功") : Result.fail("删除权限失败：数据库操作未成功");
        } catch (Exception e) {
            return Result.fail("删除权限异常：" + e.getMessage());
        }
    }

    @Override
    public Result pagePermissions(Integer pageNum, Integer pageSize) {
        IPage<Permission> page = new Page<>(pageNum, pageSize);
        IPage<Permission> permissionPage = this.page(page);
        // 将分页结果中的 Permission 列表转换为 PermissionDTO 列表
        IPage<PermissionDTO> permissionDTOPage = new Page<>(permissionPage.getCurrent(), permissionPage.getSize(), permissionPage.getTotal());
        List<PermissionDTO> permissionDTOList = permissionPage.getRecords().stream()
                .map(permission -> {
                    PermissionDTO dto = new PermissionDTO();
                    BeanUtil.copyProperties(permission, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        permissionDTOPage.setRecords(permissionDTOList);
        return Result.ok(permissionDTOPage);
    }

    @Override
    public Result searchPermissions(String permissionName) {
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Permission::getPermissionName, permissionName);
        List<Permission> permissionList = this.list(queryWrapper);
        // 将 Permission 列表转换为 PermissionDTO 列表
        List<PermissionDTO> permissionDTOList = permissionList.stream()
                .map(permission -> {
                    PermissionDTO dto = new PermissionDTO();
                    BeanUtil.copyProperties(permission, dto);
                    return dto;
                })
                .collect(Collectors.toList());
        return Result.ok(permissionDTOList);
    }
}


